<!-- bootstrap下拉框组件 -->
<template>
	<div class="dropdown" ref="dropdownRef">
		<a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click.prevent="toggleOpen">{{title}}</a>
		<ul class="dropdown-menu" style="display:block" v-if="isOpen">
			<slot></slot>
		</ul>
	</div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from "vue";
import useClickOutside from "../hooks/useClickOutside";
export default defineComponent({
	name: "DropDown",
	props: {
		title: {
			type: String,
			required: true,
		},
	},
	setup() {
		// 下拉框显示/隐藏
		const isOpen = ref(false);
		const toggleOpen = () => {
			isOpen.value = !isOpen.value;
		};

		// vue3获取dom元素 类似vue2中this.$refs.dropdownRef
		const dropdownRef = ref<null | HTMLElement>(null);
		const isClickOutside = useClickOutside(dropdownRef); // 是否点击的是元素外部的自定义函数

		watch(isClickOutside, () => {
			if (isOpen.value && isClickOutside.value) {
				// 下拉框展示且点击的是元素外部 则隐藏下拉框
				isOpen.value = false;
			}
		});

		return {
			isOpen,
			toggleOpen,
			dropdownRef,
		};
	},
});
</script>

<style>
</style>
